package com.glx.test.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;


@Component
public class JwtUtils {
    private static final String SECRET = "GLX18862092592";

    /**
     * 传入payload信息获取token
     * @param map payload
     * @return token
     */
    public static String getToken(Map<String, String> map) {
        JWTCreator.Builder builder = JWT.create();

        //payload
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 1); //默认1天过期
//        instance.add(Calendar.SECOND, 10);

        builder.withExpiresAt(instance.getTime());//指定令牌的过期时间
        return builder.sign(Algorithm.HMAC256(SECRET));
    }

    /**
     * 验证token 合法性
     */

    public static DecodedJWT verify(String token) {
            DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
            return decodedJWT;
    }



    /**
     * 获取token信息方法
     */
    public static Map<String, Claim> getTokenInfo(String token) {


        return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token).getClaims();

    }

    public static Map<String,Object> verifyToken(String authorizationHeader) {
        Map<String, Object> map = new HashMap<>();
        try {
            JwtUtils.verify(authorizationHeader);
            map.put("result","success");
            return map;
        } catch (Exception e) {
            map.put("result","fail");
            map.put("failReason","Token验证失败");
            return map;
        }
    }



}

